<?php

declare(strict_types=1);
/**
 * This file is part of habo_new_media.
 *
 * @link     https://www.berlen.cn/
 * @contact  tech@berlen.cn
 * @license  http://gitlab.rehou.cn/habo/habo_new_media/-/blob/master/README.md
 */
namespace app\command\notice;

use app\command\BaseWork;
use app\enum\NoticeEnum;
use app\service\notice\NoticeConsumerService;
use app\service\notice\NoticeService;
use think\console\Input;
use think\console\input\Argument;
use think\console\Output;
use think\facade\Cache;

/*
 * 发送提醒脚本
 */

class NoticeConsumerWork extends BaseWork
{
    protected function configure()
    {
        // 指令配置
        $this->setName('notice_consumer_work');
        // 设置参数
        $this->setDescription('发送提醒脚本消费')
            ->addArgument('index', Argument::REQUIRED, '进程id')
            ->addArgument('total', Argument::REQUIRED, '进程总数')
            ->setHelp('php think notice_consumer_work [index] [total]');
    }

    protected function execute(Input $input, Output $output)
    {
        set_time_limit(0);
        $this->getOutputMessage('发送提醒开始');
        $index = intval($input->getArgument('index'));
        $total = intval($input->getArgument('total'));
        // 超过5min就停止
        $t = time();
        $runTime = 5 * 60;
        $redis = Cache::store('redis')->handler();
        $key = NoticeEnum::NOTICE_LIST_KEY;
        while (time() - $t <= $runTime) {
            $fields = $redis->hKeys($key);
            if (! $fields) {
                $this->getOutputMessage('暂无数据');
                sleep(rand(5, 10));
                continue;
            }
            foreach ($fields as $field) {
                $num = crc32($field);
                if ($index != ($num % $total)) {
                    continue;
                }
                try {
                    $data = $redis->hGet($key, $field);
                    $arr = json_decode($data, true);
                    $name = $arr['id'] . '-' . $arr['type'] . '-' . $arr['date'];
                    $notice = NoticeService::getNotice($arr['id']);
                    $obj = new NoticeConsumerService($notice);
                    $this->getOutputMessage('发送[' . $name . ']开始');
                    if (! $obj->sendNotice()) {
                        $this->getOutputMessage('发送[' . $name . ']失败:' . $obj::getError(0));
                    } else {
                        $redis->hDel($key, $field);
                    }
                    $this->getOutputMessage('发送[' . $name . ']完成');
                } catch (\Exception $e) {
                    $this->getOutputMessage('错误：' . $e->getMessage());
                    echo $e->getLine() . PHP_EOL;
                    echo $e->getFile() . PHP_EOL;
                    echo $e->getTraceAsString() . PHP_EOL;
                }
            }
        }
        $this->getOutputMessage('发送提醒结束');
    }
}
